package com.hermit.qmst.UI.main;


import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.hermit.qmst.MainActivity;
import com.hermit.qmst.R;
import com.hermit.qmst.UI.activity.AbountActivity;
import com.hermit.qmst.UI.activity.ChangePasswordActivity;
import com.hermit.qmst.UI.activity.DialSetActivity;
import com.hermit.qmst.UI.activity.ErweimaActivity;
import com.hermit.qmst.UI.activity.ExplainActivity;
import com.hermit.qmst.UI.activity.InviteActivity;
import com.hermit.qmst.UI.activity.LoginActivity;
import com.hermit.qmst.UI.activity.MyAccountActivity;
import com.hermit.qmst.UI.activity.OpenUrlActivity;
import com.hermit.qmst.UI.activity.SelectCallActivity;
import com.hermit.qmst.UI.activity.SystemActivity;
import com.hermit.qmst.csipsimple.api.SipProfile;
import com.hermit.qmst.request.DownLoadAPK;
import com.hermit.qmst.request.RequestTask;
import com.hermit.qmst.request.RequestTaskInterface;
import com.hermit.qmst.request.UpdateProcessInterface;
import com.hermit.qmst.tools.Common;
import com.hermit.qmst.tools.ParseXML;
import com.hermit.qmst.tools.Preferences;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

/**
 * A simple {@link Fragment} subclass.
 */
public class MoreFragment extends Activity implements View.OnClickListener, RequestTaskInterface, UpdateProcessInterface {


    private ProgressBar mProgressBar;
    private AlertDialog mProgressDialog;
    private int requestType = 0;
    private String mAPKUrlPath = "";
    private TextView mTitle;
    private TextView mtvServiceCall;
    private Preferences mPreferences;
    private RequestQueue mRequestQueue;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_tab_more);
        mPreferences = new Preferences(this);
        if (mRequestQueue == null) {
            mRequestQueue = Volley.newRequestQueue(this);
        }
        mRequestQueue.getCache().clear();
        initView();
        request_more_info();

    }


    private void initView() {
        findViewById(R.id.rlyt_balance).setOnClickListener(this);
        findViewById(R.id.rlyt_setpwd).setOnClickListener(this);
        findViewById(R.id.rlyt_recommend).setOnClickListener(this);
        findViewById(R.id.rlyt_explain).setOnClickListener(this);
        findViewById(R.id.rlyt_about).setOnClickListener(this);
        findViewById(R.id.rlyt_exit).setOnClickListener(this);
        findViewById(R.id.rlyt_setdial).setOnClickListener(this);
        findViewById(R.id.rlyt_new).setOnClickListener(this);
        findViewById(R.id.rlyt_hezuo).setOnClickListener(this);
        findViewById(R.id.rlyt_recharge).setOnClickListener(this);
        findViewById(R.id.rlyt_share).setOnClickListener(this);
        findViewById(R.id.rlyt_update).setOnClickListener(this);
        findViewById(R.id.rlyt_website).setOnClickListener(this);
        findViewById(R.id.rlyt_mingpian).setOnClickListener(this);
        findViewById(R.id.rlyt_flow_recharge).setOnClickListener(this);
        mTitle = (TextView) findViewById(R.id.tv_title);
        mTitle.setText("更多");
        mtvServiceCall = (TextView) findViewById(R.id.tv_title_right);

//        if (mPreferences.getPreferenceStringValue(Preferences.SERVICE_CALL) != null)
//        {
//            mtvServiceCall.setText("  客服电话  ");
//            mtvServiceCall.setVisibility(View.VISIBLE);
//            mtvServiceCall.setOnClickListener(this);
//        }

        ((ImageView) findViewById(R.id.iv_title_left)).setImageResource(R.drawable.ic_back);
        findViewById(R.id.iv_title_left).setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        Intent intent;
        switch (v.getId()) {

            case R.id.rlyt_balance:

                intent = new Intent(MoreFragment.this, MyAccountActivity.class);
                startActivity(intent);
                overridePendingTransition(R.anim.fling_in_right2left, R.anim.fling_out_left2right);

                break;
            case R.id.rlyt_setpwd:
                intent = new Intent(MoreFragment.this, ChangePasswordActivity.class);
                startActivity(intent);
                overridePendingTransition(R.anim.fling_in_right2left, R.anim.fling_out_left2right);
                break;

            case R.id.rlyt_recommend:
                intent = new Intent(MoreFragment.this, InviteActivity.class);
                startActivity(intent);
                overridePendingTransition(R.anim.fling_in_right2left, R.anim.fling_out_left2right);
                break;

            case R.id.rlyt_website:

                String url = mPreferences.getPreferenceStringValue(Preferences.WEBSITE);
                if (url != null) {
                    intent = new Intent(MoreFragment.this, OpenUrlActivity.class);
                    intent.putExtra("title", "官网");
                    intent.putExtra("url", url);
                    startActivity(intent);
                    overridePendingTransition(R.anim.fling_in_right2left, R.anim.fling_out_left2right);
                }
                break;
            case R.id.rlyt_flow_recharge:
                intent = new Intent(MoreFragment.this, OpenUrlActivity.class);
                intent.putExtra("title", "流量充值");
                intent.putExtra("url", "http://120.26.91.35/net/net_pay.php?action=pay_send&webid=2");
                startActivity(intent);
                overridePendingTransition(R.anim.fling_in_right2left, R.anim.fling_out_left2right);

                break;

            case R.id.rlyt_mingpian:

                intent = new Intent(MoreFragment.this, ErweimaActivity.class);
                startActivity(intent);
                //getActivity().overridePendingTransition(R.anim.fling_in_right2left, R.anim.fling_out_left2right);
                break;

            case R.id.rlyt_explain:
                intent = new Intent(MoreFragment.this, ExplainActivity.class);
                startActivity(intent);
                overridePendingTransition(R.anim.fling_in_right2left, R.anim.fling_out_left2right);

                break;
            case R.id.rlyt_about:

                intent = new Intent(MoreFragment.this, AbountActivity.class);
                startActivity(intent);
                overridePendingTransition(R.anim.fling_in_right2left, R.anim.fling_out_left2right);
                break;

            case R.id.rlyt_setdial:

                intent = new Intent(MoreFragment.this, DialSetActivity.class);
                startActivity(intent);
                overridePendingTransition(R.anim.fling_in_right2left, R.anim.fling_out_left2right);
                break;

            case R.id.rlyt_exit:


                Preferences p = new Preferences(MoreFragment.this);
                p.setPreferenceStringValue(Preferences.MY_PHONE, null);
                p.setPreferenceStringValue(Preferences.MY_PASSWORD, null);
                p.setPreferenceStringValue(Preferences.SIP_ACCOUNT, "");

                ArrayList<SipProfile> accounts = new ArrayList<SipProfile>();

                accounts = SipProfile
                        .getAllProfiles(
                                this,
                                false,
                                new String[]{
                                        SipProfile.FIELD_ID,
                                        SipProfile.FIELD_ACC_ID,
                                        SipProfile.FIELD_ACTIVE,
                                        SipProfile.FIELD_DISPLAY_NAME,
                                        SipProfile.FIELD_WIZARD,
                                        SipProfile.FIELD_USERNAME});

                if (accounts != null && accounts.size() > 0) {

                    try {
                        MainActivity.getInstant().mISipService
                                .removeAllAccounts();
                        getContentResolver().delete(
                                SipProfile.ACCOUNT_URI,
                                null, null);
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                }

                intent = new Intent(MoreFragment.this, LoginActivity.class);
                startActivity(intent);

                MainActivity.getInstance().finish();

                break;
            case R.id.rlyt_new:
                intent = new Intent(MoreFragment.this, SystemActivity.class);
                startActivity(intent);
                overridePendingTransition(R.anim.fling_in_right2left, R.anim.fling_out_left2right);

                break;
            case R.id.rlyt_hezuo:
                intent = new Intent(MoreFragment.this, OpenUrlActivity.class);
                intent.putExtra("title", "");
                intent.putExtra("url", mPreferences.getPreferenceStringValue("4"));
                startActivity(intent);
                overridePendingTransition(R.anim.fling_in_right2left, R.anim.fling_out_left2right);

                break;
            case R.id.rlyt_recharge:
                intent = new Intent(MoreFragment.this, OpenUrlActivity.class);
                intent.putExtra("title", "");
                intent.putExtra("url", mPreferences.getPreferenceStringValue("5"));
                startActivity(intent);
                overridePendingTransition(R.anim.fling_in_right2left, R.anim.fling_out_left2right);

                break;
            case R.id.rlyt_update:

                checkUpdateAPK();


                break;

            case R.id.tv_title_right:

                String phone = mPreferences.getPreferenceStringValue(Preferences.SERVICE_CALL);
                if (phone != null) {
                    Common.mCallName = "客服电话";
                    Common.mCallPhone = phone;
                    intent = new Intent(MoreFragment.this, SelectCallActivity.class);
                    startActivity(intent);
                }


                break;

            case R.id.iv_title_left:
                finish();
                break;

            default:
                break;
        }

    }


    private void request_more_info() {

        mRequestQueue.getCache().clear();
        String url = Common.submitQueryMoreInfoPath();

        StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {

                try {
                    if (ParseXML.parseResponseXML(s, "Ret").equals("0")) {
                        String service_call = ParseXML.parseResponseXML(s, "service_call");
                        if (service_call != null && service_call.length() > 0) {
                            mtvServiceCall.setVisibility(View.VISIBLE);
                            mPreferences.setPreferenceStringValue(Preferences.SERVICE_CALL, service_call);
                        } else {
                            mtvServiceCall.setVisibility(View.GONE);
                            mPreferences.setPreferenceStringValue(Preferences.SERVICE_CALL, null);
                        }

                        String website = ParseXML.parseResponseXML(s, "website");
                        if (website != null && website.length() > 0) {
                            mPreferences.setPreferenceStringValue(Preferences.WEBSITE, website);
                        } else {
                            mPreferences.setPreferenceStringValue(Preferences.WEBSITE, null);
                        }
                    }
                } catch (Exception e) {

                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        }) {
            @Override
            public byte[] getBody() {
                String requestParam = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><data><type>more_info</type><uid>" + Common.mInfoId + "</uid><phone>" + Common.myPhone + "</phone></data>";
                byte[] b = null;
                try {
                    b = requestParam.getBytes("utf-8");
                } catch (Exception e) {
                    b = requestParam.getBytes();
                }
                return b;
            }
        };

        mRequestQueue.add(request);


    }


    private void checkUpdateAPK() {
        mProgressDialog = ProgressDialog.show(MoreFragment.this, "提示", "系统正在处理，请稍后…", false, false);
        mProgressDialog.setCancelable(true);
        requestType = 1;
        String url = Common.submitUpdatePath();
        RequestTask _RequestTask = new RequestTask(this, url, "", "POST", this);
        _RequestTask.execute();
    }


    private void showUpdateVersionDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("软件更新")
                .setMessage("检查到新的版本,是否更新")
                .setPositiveButton("更新", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        showUpdateDialog();
                        downloadAPK();

                    }
                }).setNegativeButton("暂不更新", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        }).show();
    }

    private void downloadAPK() {
        requestType = 2;
        if (mAPKUrlPath.length() > 0) {
            DownLoadAPK downLoadAPK = new DownLoadAPK(this, mAPKUrlPath, this, MoreFragment.this);
            downLoadAPK.execute();
        }

    }

    private void showUpdateDialog() {
        View v = LayoutInflater.from(this).inflate(R.layout.update_probar, null);
        mProgressBar = (ProgressBar) v.findViewById(R.id.progressBar1);

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("正在更新...                              ")

                .setView(v);

        mProgressDialog = builder.create();
        mProgressDialog.show();

    }

    @Override
    public void postExecute(String paramString) {
        if (requestType == 1) {


            if (mProgressDialog != null) {
                mProgressDialog.dismiss();

            }
            if (paramString == null || paramString.length() == 0) {
                Toast.makeText(MoreFragment.this, "当前是最新版本", Toast.LENGTH_LONG).show();
                return;
            }


            String code = ParseXML.parseResponseXML(paramString, "Ret");

            if (code != null && code.equals("0")) {
                mAPKUrlPath = ParseXML.parseResponseXML(paramString, "url");
                showUpdateVersionDialog();
            } else {
                Toast.makeText(MoreFragment.this, "当前是最新版本", Toast.LENGTH_LONG).show();
            }
        }
        if (requestType == 2) {

            if (mProgressDialog != null) {
                mProgressDialog.dismiss();
            }
            String fileName = Environment.getExternalStorageDirectory() + "/" + Common.mApkName;
            if (paramString.equals(fileName)) {
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setDataAndType(Uri.fromFile(new File(paramString)), "application/vnd.android.package-archive");
                startActivity(intent);
            } else {
                String[] command = {"chmod", "777", paramString};
                ProcessBuilder builder = new ProcessBuilder(command);
                try {
                    builder.start();

                    Intent intent = new Intent(Intent.ACTION_VIEW);
                    intent.setDataAndType(Uri.fromFile(new File(paramString)), "application/vnd.android.package-archive");
                    startActivity(intent);

                } catch (IOException e) {

                    // TODO Auto-generated catch block

                    e.printStackTrace();

                }
            }
        }


    }

    @Override
    public void processUpate(int value) {
        mProgressBar.setProgress(value);

    }

}
